package com.yanqu.road.server.manager.activity.dragonboatrace;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.dragonboatrace.DragonBoatRaceMemberRecord;
import com.yanqu.road.entity.activity.dragonboatrace.config.DragonBoatRacePlaceConfig;
import com.yanqu.road.entity.activity.dragonboatrace.DragonBoatRaceUnionData;
import com.yanqu.road.entity.activity.dragonboatrace.DragonBoatRaceVoyageRecord;
import com.yanqu.road.entity.log.LogDragonBoatRaceUnionDistance;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.logic.bussiness.activity.DragonBoatRaceBusiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.dragonboatrace.DragonBoatRaceProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.manager.union.CrossUnionConfigMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description
 * @Author cwq
 * @Data 2022/2/15 16:02
 */
public class DragonBoatRaceActivity {

    public int activityId;

    public Map<String, DragonBoatRaceUnionData> unionMap = new ConcurrentHashMap<>();

    public DragonBoatRaceActivity(int activityId) {
        this.activityId = activityId;
        // 加载配置
        DragonBoatRaceConfigMgr.reloadConfig(activityId);
        initDB();
    }

    public void initDB() {
        unionMap = DragonBoatRaceBusiness.getDragonBoatRaceUnionDataMap(activityId);
        for (DragonBoatRaceUnionData item : unionMap.values()) {
            sortDragonBoatRaceUnionRecord(item);
            int maxMemberSize = getUnionMaxMemberSize(item);
            maxMemberSize = Math.min(maxMemberSize, item.getRecordList().size());
            for (int i = 0; i < maxMemberSize; i++) {
                DragonBoatRaceVoyageRecord record = item.getRecordList().get(i);
                item.setTodayUnionDistance(item.getTodayUnionDistance() + record.getDistance());
            }
        }
    }

    public boolean save() {
        for (DragonBoatRaceUnionData item : unionMap.values()) {
            if (item.isInsertOption()) {
                DragonBoatRaceBusiness.addDragonBoatRaceUnionData(item);
            } else if (item.isUpdateOption()) {
                DragonBoatRaceBusiness.updateDragonBoatRaceUnionData(item);
            }
        }
        return true;
    }

    /**
     * 每日航行记录 排序
     *
     * @param item
     */
    public static void sortDragonBoatRaceUnionRecord(DragonBoatRaceUnionData item) {
        synchronized (item) {
            item.getRecordList().sort((t1, t2) -> {
                if (t1.getDistance() != t2.getDistance()) {
                    return Long.compare(t2.getDistance(), t1.getDistance());
                } else {
                    return Long.compare(t1.getUpdateTime(), t2.getUpdateTime());
                }
            });
        }
    }

    /**
     * 进入地图
     *
     * @param unionId
     * @param placeId
     */
    public DragonBoatRaceProto.DragonBoatRaceEnterMapRespMsg.Builder enterMap(String unionId, int placeId) {
        DragonBoatRaceProto.DragonBoatRaceEnterMapRespMsg.Builder builder = DragonBoatRaceProto.DragonBoatRaceEnterMapRespMsg.newBuilder();
        DragonBoatRaceUnionData dragonBoatRaceUnionData = unionMap.get(unionId);
        if (dragonBoatRaceUnionData != null) {
            builder.setUnionDistance(getUnionDistance(dragonBoatRaceUnionData));
            for (Map.Entry<Integer, List<Long>> entry : dragonBoatRaceUnionData.getReceivedInfoMap().entrySet()) {
                builder.addUnionReceivedRecords(DragonBoatRaceProto.DragonBoatRaceUnionReceivedRecordEntity.newBuilder().setId(entry.getKey()).setTimes(entry.getValue().size()));
            }
        }
        builder.setPlaceId(placeId);
        builder.setRet(0);
        return builder;
    }

    public DragonBoatRaceProto.DragonBoatRaceGetReceivedRecordRespMsg.Builder getPlaceReceived(String unionId, int placeId) {
        DragonBoatRaceProto.DragonBoatRaceGetReceivedRecordRespMsg.Builder builder = DragonBoatRaceProto.DragonBoatRaceGetReceivedRecordRespMsg.newBuilder();
        DragonBoatRaceUnionData dragonBoatRaceUnionData = unionMap.get(unionId);
        if (dragonBoatRaceUnionData != null) {
            synchronized (dragonBoatRaceUnionData){
                List<Long> list = dragonBoatRaceUnionData.getReceivedInfoMap().get(placeId);
                if (list != null) {
                    for (Long memberId : list) {
                        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberId);
                        if (userBaseInfo != null) {
                            builder.addNameList(userBaseInfo.getNickName());
                        }
                    }
                }
            }
        }
        builder.setRet(0);
        return builder;
    }

    public DragonBoatRaceProto.DragonBoatRaceGetUnionRecordRespMsg.Builder getUnionRecord(String unionId) {
        DragonBoatRaceProto.DragonBoatRaceGetUnionRecordRespMsg.Builder builder = DragonBoatRaceProto.DragonBoatRaceGetUnionRecordRespMsg.newBuilder();
        DragonBoatRaceUnionData unionData = unionMap.get(unionId);
        if (unionData != null) {
            // 有联盟
            synchronized (unionData) {
                Map<Long, DragonBoatRaceMemberRecord> memberRecordMap = unionData.getMemberRecordMap();
                for (DragonBoatRaceMemberRecord item : memberRecordMap.values()) {
                    DragonBoatRaceProto.DragonBoatRaceMemberRecordEntity.Builder memberRecordEntity = DragonBoatRaceProto.DragonBoatRaceMemberRecordEntity.newBuilder();
                    memberRecordEntity.setUserId(item.getuId());
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(item.getuId());
                    if (userBaseInfo != null) {
                        memberRecordEntity.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                    }
                    memberRecordEntity.setTimes(item.getT());
                    for (Map.Entry<Long, Long> entry : item.getRecord().entrySet()) {
                        DragonBoatRaceProto.DragonBoatRaceDailyRecordEntity.Builder dailyRecordEntity = DragonBoatRaceProto.DragonBoatRaceDailyRecordEntity.newBuilder();
                        dailyRecordEntity.setTime(entry.getKey() * 1000);
                        dailyRecordEntity.setDistance(entry.getValue());
                        memberRecordEntity.addDailyRecordList(dailyRecordEntity);
                    }
                    builder.addRecordList(memberRecordEntity);
                }
            }
        }
        builder.setRet(0);
        return builder;
    }

    public DragonBoatRaceProto.DragonBoatRaceGetVoyageRecordRespMsg.Builder getVoyageRecord(String unionId) {
        DragonBoatRaceProto.DragonBoatRaceGetVoyageRecordRespMsg.Builder builder = DragonBoatRaceProto.DragonBoatRaceGetVoyageRecordRespMsg.newBuilder();
        DragonBoatRaceUnionData dragonBoatRaceUnionData = unionMap.get(unionId);
        if (dragonBoatRaceUnionData != null) {
            // 刷新记录
            synchronized (dragonBoatRaceUnionData) {
                refreshVoyageRecord(dragonBoatRaceUnionData);
                sortDragonBoatRaceUnionRecord(dragonBoatRaceUnionData);
                // 排序
                for (DragonBoatRaceVoyageRecord item : dragonBoatRaceUnionData.getRecordList()) {
                    DragonBoatRaceProto.DragonBoatRaceVoyageRecordEntity.Builder record = DragonBoatRaceProto.DragonBoatRaceVoyageRecordEntity.newBuilder();
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(item.getRoleId());
                    if (userBaseInfo != null) {
                        record.setMemberName(userBaseInfo.getNickName());
                    }
                    record.setDistance(item.getDistance());
                    record.setTimes(item.getTimes());
                    builder.addRecordList(record);
                }
            }
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 领取奖励
     *
     * @param unionId
     * @param userId
     * @param placeId
     * @return
     */
    public DragonBoatRaceProto.DragonBoatRaceReceiveRecordRewardRespMsg.Builder receiveRecord(String unionId, long userId, int placeId) {
        DragonBoatRaceProto.DragonBoatRaceReceiveRecordRewardRespMsg.Builder builder = DragonBoatRaceProto.DragonBoatRaceReceiveRecordRewardRespMsg.newBuilder();
        DragonBoatRaceUnionData unionData = unionMap.get(unionId);
        // 判断该任务是否完成
        if (unionData == null) {
            builder.setRet(GameErrorCode.E_DRAGONBOATRACE_NOT_CONDITIONS_OF_AWARD);
            return builder;
        }
        DragonBoatRaceConfig config = DragonBoatRaceConfigMgr.getConfigMap(activityId);
        if (config == null) {
            builder.setRet(GameErrorCode.E_DRAGONBOATRACE_PLACE_CONFIG_NO_FOUND);
            return builder;
        }
        DragonBoatRacePlaceConfig placeConfig = config.placeConfigMap.get(placeId);
        if (placeConfig == null) {
            builder.setRet(GameErrorCode.E_DRAGONBOATRACE_PLACE_CONFIG_NO_FOUND);
            return builder;
        }
        if (getUnionDistance(unionData) < placeConfig.getDistance()) {
            builder.setRet(GameErrorCode.E_DRAGONBOATRACE_NOT_CONDITIONS_OF_AWARD);
            return builder;
        }
        synchronized (unionData) {
            Map<Integer, List<Long>> receivedInfoMap = unionData.getReceivedInfoMap();
            List<Long> list = receivedInfoMap.get(placeId);
            int maxMemberCount = getUnionMaxMemberSize(unionData);
            if (list != null) {
                if (list.contains(userId)) {
                    builder.setRet(GameErrorCode.E_ACTIVITY_REWARD_IS_GET);
                    return builder;
                }
                if (list.size() >= maxMemberCount) {
                    builder.setRet(GameErrorCode.E_UNION_ACTIVITY_RECHARGE_USER_MAX);
                    return builder;
                }
            } else {
                list = new ArrayList<>();
                receivedInfoMap.put(placeId, list);
            }
            // 领取奖励
            list.add(userId);
            unionData.setUpdateOption();
            // 如果领取满了需要刷新盟友红点
            if (list.size() >= maxMemberCount) {
                synDistanceAndReceiveInfoToMember(unionId);
            }
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 联盟增加航行记录
     *
     * @param unionId
     * @param userId
     * @param distance
     * @param cutTime
     */
    public void addDragonBoatRaceVoyageRecord(String unionId, long userId, long distance, long cutTime, UnionBaseInfo unionBase) {
        DragonBoatRaceUnionData unionData = getDragonBoatRaceUnionData(unionId, unionBase, true);
        synchronized (unionData) {
            // 刷新每日航行记录
            refreshVoyageRecord(unionData);
            int time = (int)(cutTime / 1000);
            DragonBoatRaceVoyageRecord myRecord = unionData.getRecordMap().get(userId);
            if (myRecord == null) {
                myRecord = new DragonBoatRaceVoyageRecord();
                myRecord.setRoleId(userId);
                unionData.getRecordMap().put(userId, myRecord);
                unionData.getRecordList().add(myRecord);
            }
            myRecord.setTimes(myRecord.getTimes() + 1);
            myRecord.setUpdateTime(time);
            myRecord.setDistance(myRecord.getDistance() + distance);
            // 刷新联盟商会距离
            refreshUnionScore(unionData);
            // 商会成员航行记录
            addDragonBoatRaceMemberRecord(unionData, userId, distance, time);
            long totalDistance = getUnionDistance(unionData);
            int unionLevel = CrossUnionConfigMgr.getUnionLv(unionBase.getExperience());
//            DragonBoatRaceLogMgr.addLogDragonBoatRaceUnionDistance(new LogDragonBoatRaceUnionDistance(activityId, unionId, unionLevel, userId, (int) distance, totalDistance, cutTime));
            CrossAutoLogMgr.add(new LogDragonBoatRaceUnionDistance(activityId, unionId, unionLevel, userId, (int) distance, totalDistance, cutTime));
        }
    }

    public DragonBoatRaceProto.DragonBoatRaceSynUnionInfoCrossToGameMsg.Builder getDistanceAndReceivedInfo(String unionId) {
        DragonBoatRaceUnionData unionData = getDragonBoatRaceUnionData(unionId, null, false);
        if (unionData == null) {
            return null;
        }
        DragonBoatRaceProto.DragonBoatRaceSynUnionInfoCrossToGameMsg.Builder builder = DragonBoatRaceProto.DragonBoatRaceSynUnionInfoCrossToGameMsg.newBuilder();
        synchronized (unionData) {
            builder.setTotalDistance(getUnionDistance(unionData));
            builder.setUnionId(unionData.getUnionId());
            for (Map.Entry<Integer, List<Long>> entry : unionData.getReceivedInfoMap().entrySet()) {
                int placeId = entry.getKey();
                List<Long> receiveList = entry.getValue();
                builder.addReceiveInfoList(DragonBoatRaceProto.DragonBoatRaceTimesReceiveInfo.newBuilder().setPlace(placeId).addAllReceiveList(receiveList));
            }
        }
        return builder;
    }


    /**
     * 刷新每日航行记录
     *
     * @param dragonBoatRaceUnionData
     */
    public static void refreshVoyageRecord(DragonBoatRaceUnionData dragonBoatRaceUnionData) {
        if (DateHelper.getDiffDayNum(dragonBoatRaceUnionData.getRecordRefreshTime()) > 0) {
            synchronized (dragonBoatRaceUnionData) {
                if (DateHelper.getDiffDayNum(dragonBoatRaceUnionData.getRecordRefreshTime()) > 0) {
                    dragonBoatRaceUnionData.setDistance(getUnionDistance(dragonBoatRaceUnionData));
                    dragonBoatRaceUnionData.setTodayUnionDistance(0);
                    dragonBoatRaceUnionData.getRecordList().clear();
                    dragonBoatRaceUnionData.getRecordMap().clear();
                    dragonBoatRaceUnionData.setRecordRefreshTime((int) (System.currentTimeMillis() / 1000));
                }
            }
        }
    }

    public static long getUnionDistance(DragonBoatRaceUnionData dragonBoatRaceUnionData) {
        return dragonBoatRaceUnionData.getDistance() + dragonBoatRaceUnionData.getTodayUnionDistance();
    }

    /**
     * 刷新联盟积分
     */
    public void refreshUnionScore(DragonBoatRaceUnionData dragonBoatRaceUnionData) {
        int maxMemberSize = getUnionMaxMemberSize(dragonBoatRaceUnionData);
        sortDragonBoatRaceUnionRecord(dragonBoatRaceUnionData);
        long oldTodayDistance = dragonBoatRaceUnionData.getTodayUnionDistance();
        long newTodayDistance = 0;
        maxMemberSize = Math.min(maxMemberSize, dragonBoatRaceUnionData.getRecordList().size());
        for (int i = 0; i < maxMemberSize; i++) {
            DragonBoatRaceVoyageRecord record = dragonBoatRaceUnionData.getRecordList().get(i);
            newTodayDistance += record.getDistance();
        }
        if (oldTodayDistance != newTodayDistance) {
            dragonBoatRaceUnionData.setTodayUnionDistance(newTodayDistance);
            oldTodayDistance += dragonBoatRaceUnionData.getDistance();
            newTodayDistance += dragonBoatRaceUnionData.getDistance();
            // 像联盟的那台跨服 同步现在联盟领取的数据  然后再广播给联盟玩家
            attemptSynUnionMemberRedPoint(oldTodayDistance, newTodayDistance, dragonBoatRaceUnionData.getUnionId());
        }
    }

    /**
     * 新增距离尝试刷新盟友红点
     */
    public void attemptSynUnionMemberRedPoint(long oldDistance, long newDistance, String unionId) {
        DragonBoatRaceConfig config = DragonBoatRaceConfigMgr.getConfigMap(activityId);
        if (config != null) {
            for (DragonBoatRacePlaceConfig item : config.placeConfigList) {
                if (newDistance < item.getDistance()) {
                    return;
                }
                if (oldDistance < item.getDistance()) {
                    // 解锁新地方 尝试给所有盟友发红点
                    // 给跨服发数据
                    synDistanceAndReceiveInfoToMember(unionId);
                    return;
                }
            }
        }
    }

    /**
     * 同步联盟航行距离和领取信息 给联盟成员 刷新红点用
     *
     * @param unionId
     */
    public void synDistanceAndReceiveInfoToMember(String unionId) {
        // 给各个区服
        ActivityInfo activityInfo = ActivityMgr.getActivityInfo(activityId);
        if (activityInfo == null) {
            return;
        }
        DragonBoatRaceProto.DragonBoatRaceSynUnionInfoCrossToGameMsg.Builder crossToCross2Msg = getDistanceAndReceivedInfo(unionId);
        crossToCross2Msg.setType(0);
        for (Long serverId : activityInfo.getServerIdList()) {
            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_DRAGONBOATRACE_DISTANCE_AND_RECEIVED_INFO_FROM_CROSS, crossToCross2Msg));
        }


    }


    /**
     * 同步联盟信息
     */
    public void synUnionInfo(String unionId, int type, UnionBaseInfo unionBase) {
        DragonBoatRaceUnionData unionData = unionMap.get(unionId);
        if (unionData == null) {
            return;
        }
        synchronized (unionData) {
            unionData.setUnionBaseInfo(unionBase);
            unionData.setUpdateOption();
            if (type == 0) {
                synDistanceAndReceiveInfoToMember(unionId);
            }
        }
    }

    /**
     * /**
     * 获取联盟成员最大上限
     *
     * @param unionData
     * @return
     */
    public static int getUnionMaxMemberSize(DragonBoatRaceUnionData unionData) {
        if (unionData == null || unionData.getUnionBaseInfo() == null) {
            return 0;
        }
        int crossServerCount = CrossUnionServerGroupMgr.getGroupServerCountByServerId(unionData.getUnionBaseInfo().getServerId());
        return CrossUnionConfigMgr.getMaxMemberCount(unionData.getUnionBaseInfo().getExperience(), unionData.getUnionBaseInfo().isCross(), crossServerCount);
    }

    public DragonBoatRaceUnionData getDragonBoatRaceUnionData(String unionUid, UnionBaseInfo unionBase, boolean newIfNull) {
        DragonBoatRaceUnionData dragonBoatRaceUnionData = unionMap.get(unionUid);
        if (dragonBoatRaceUnionData == null && newIfNull) {
            synchronized (unionMap) {
                dragonBoatRaceUnionData = unionMap.get(unionUid);
                if (dragonBoatRaceUnionData == null) {
                    dragonBoatRaceUnionData = new DragonBoatRaceUnionData();
                    dragonBoatRaceUnionData.setActivityId(activityId);
                    dragonBoatRaceUnionData.setRecordRefreshTime((int) (System.currentTimeMillis() / 1000));
                    dragonBoatRaceUnionData.setUnionId(unionUid);
                    dragonBoatRaceUnionData.setUnionBaseInfo(unionBase);
                    dragonBoatRaceUnionData.setInsertOption();
                    unionMap.put(unionUid, dragonBoatRaceUnionData);
                }
            }
        }
        if (dragonBoatRaceUnionData != null && unionBase != null && newIfNull) {
            synchronized (dragonBoatRaceUnionData) {
                dragonBoatRaceUnionData.setUnionBaseInfo(unionBase);
            }
        }
        return dragonBoatRaceUnionData;
    }


    public void addDragonBoatRaceMemberRecord(DragonBoatRaceUnionData dragonBoatRaceUnionData, long userId, long distance, long time) {
        DragonBoatRaceMemberRecord memberRecord = dragonBoatRaceUnionData.getMemberRecordMap().get(userId);
        if (memberRecord == null) {
            memberRecord = new DragonBoatRaceMemberRecord();
            memberRecord.setuId(userId);
            dragonBoatRaceUnionData.getMemberRecordMap().put(userId, memberRecord);
        }
        memberRecord.setT(memberRecord.getT() + 1);
        memberRecord.getRecord().put(time, distance);
        dragonBoatRaceUnionData.setUpdateOption();
    }


}
